//
//  BuyViewController.m
//  忘不了
//
//  Created by rimi on 16/7/11.
//  Copyright © 2016年 handuan. All rights reserved.
//

#import "BuyViewController.h"
#import "SDAutoLayout.h"
#import "BaseRequest.h"
#import "BaseRequest+Buy.h"
#import "CustomProductCollectionViewCell.h"
#import "BuyList.h"
#import "UIColor+Expand.h"
#import "CustomFooter.h"
#import "MBProgressHUD.h"
#import "CheckWeb.h"
//#import "HDAlertView.h"

@interface BuyViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,CustomProductDelegate>
//篮子
@property (nonatomic, strong)UIImageView *basketImage;
@property (nonatomic, strong)UICollectionView *collectionView;
@property (nonatomic, strong)UIView *optionsView;
//总的数据源
@property (nonatomic, strong)NSMutableArray *dataSource;
//分类数据源
@property (nonatomic, strong)NSMutableArray *optionsDataSource;
//选择要买的东西
@property (nonatomic, strong)NSMutableArray *selectDataSource;
//种类图片
@property (nonatomic, strong)UIImageView *typeImage;
//表的数组
@property (nonatomic, strong)NSArray *formArr;
//当前点击的button
@property (nonatomic, strong)UIButton *selectButton;
//弹出View
@property (nonatomic, strong)UIView *addView;
//弹出View大背景
@property (nonatomic, strong)UIView *bigBackGroundView;

//查看购物清单
- (void)toBuyList;
//数据持久化清单
- (void)putInCoreDataWithData:(NSMutableArray *)data;
//添加cell
- (void)addCell:(UIButton *)sender;
//弹出提示
- (UIView *)alertView;
- (UIView *)returnBigBackGroundView;
//从网络获取数据源
- (void)getDataFromWeb;
//错误提示
- (UIView *)noWebAlertWithMessage:(NSString *)message;
@end

@implementation BuyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"购物";
    [self inializeUserInterface];
    [self inializeDataSource];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    UIView *view = [self.view viewWithTag:1001];
    UIView *bigView = [self.view viewWithTag:1002];
    [bigView removeFromSuperview];
    [view removeFromSuperview];
    
}
- (void)inializeDataSource{
    self.selectDataSource = [NSMutableArray array];
    self.dataSource = @[].mutableCopy;
    self.formArr = @[@"Vegetable",@"Fruit",@"Meat",@"Food",@"Life",@"Tools"];
    NSArray *shoppingData = [[NSUserDefaults standardUserDefaults] objectForKey:@"shoppingData"];
    if (shoppingData != nil) {
        self.dataSource = [NSMutableArray arrayWithArray:shoppingData];
        self.optionsDataSource = [NSMutableArray arrayWithArray:self.dataSource[0]];
        [self.collectionView reloadData];
    }else{
        BOOL isWeb = [CheckWeb checkWang];
        NSLog(@"%d",isWeb);
        if (isWeb == NO) {
            UIAlertController *tip3 = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请检查网络" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self.navigationController popViewControllerAnimated:YES];
            }];
            [tip3 addAction:sure];
            [self presentViewController:tip3 animated:YES completion:nil];
        }else{
            [self getDataFromWeb];
        }
    }
    
}
- (void)inializeUserInterface{
    self.view.backgroundColor = [UIColor colorWithRed:0.3752 green:0.7173 blue:1.0 alpha:1.0];
    //查看清单
    UIBarButtonItem *checkList = [[UIBarButtonItem alloc]initWithTitle:@"查看清单" style:UIBarButtonItemStylePlain target:self action:@selector(toBuyList)];
    self.navigationItem.rightBarButtonItem = checkList;
    
    //背景
    UIImageView *backImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"s"]];
    backImage.frame = self.view.frame;
    [self.view addSubview:backImage];
    //菜篮子
    self.basketImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"basket"]];
    [self.view addSubview:self.basketImage];
    self.basketImage.sd_layout
    .topSpaceToView(self.view,80)
    .centerXIs(self.view.frame.size.width / 2)
    .widthIs(self.view.frame.size.width / 2)
    .heightIs(self.view.frame.size.width /2 );
    
    //选项按钮
    self.optionsView = [[UIView alloc]init];
    self.optionsView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_optionsView];
    self.optionsView.sd_layout
    .topSpaceToView(self.basketImage,50)
    .centerXIs(self.view.frame.size.width / 2)
    .widthIs(self.view.frame.size.width)
    .heightIs(self.view.frame.size.height / 15);
    NSArray *buttonTitleArr = @[@"蔬菜",@"水果",@"肉类",@"粮食",@"生活",@"工具"];
    NSArray *imageArr = @[@"蔬菜",@"水果",@"肉",@"粮食",@"生活用品",@"工具"];
    for (NSInteger index = 0; index < 6; index ++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.tag = 100 + index;
        [button setTitle:buttonTitleArr[index] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"分类标题.jpg"] forState:UIControlStateNormal];
        [button.layer setBorderColor:[UIColor whiteColor].CGColor];
        [button setTitleColor:[UIColor colorWithRed:0.1185 green:0.7514 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(optionSbuttonpresented:) forControlEvents:UIControlEventTouchUpInside];
        [button.titleLabel setTextAlignment:NSTextAlignmentCenter];
        [self.optionsView addSubview:button];
        button.sd_layout
        .topSpaceToView(self.optionsView,0)
        .leftSpaceToView(self.optionsView,index * (self.optionsView.bounds.size.width / 6))
        .bottomSpaceToView(self.optionsView,0)
        .widthIs(self.view.frame.size.width / 6);
        
        if  (index == 0) {
            self.selectButton = button;
            [self.selectButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        }
        
        self.typeImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:imageArr[index]]];
        self.typeImage.tag = 300 + index;
        [self.view addSubview:self.typeImage];
        self.typeImage.sd_layout
        .centerXEqualToView(button)
        .bottomSpaceToView(self.optionsView,0)
        .widthIs(CGRectGetHeight(self.view.bounds) * 0.05)
        .heightIs(CGRectGetHeight(self.view.bounds) * 0.05);
    }
    
    //collectionView
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.itemSize = CGSizeMake(60, 30);
    layout.minimumLineSpacing = 5;
    layout.minimumInteritemSpacing = 5;
//    layout.footerReferenceSize = CGSizeMake(200, 60);
    layout.footerReferenceSize = CGSizeMake(CGRectGetWidth(self.view.bounds), CGRectGetWidth(self.view.bounds) /5);
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.contentInset = UIEdgeInsetsMake(10, 10, 0, 10);
    self.collectionView.backgroundColor = [UIColor colorWithRed:1.0 green:0.9649 blue:0.0605 alpha:0.2];
    //注册cell
    [self.collectionView registerClass:[CustomProductCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    //注册footer
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    self.collectionView.sd_layout
    .topSpaceToView(self.optionsView,0)
    .leftSpaceToView(self.view,0)
    .rightSpaceToView(self.view,0)
    .bottomSpaceToView(self.view,0);
    self.addView = [[UIView alloc]init];
}
- (void)addCell:(UIButton *)sender{
    sender.selected = YES;
    UIView *bigView = [self returnBigBackGroundView];
    UIView *view = [self alertView];
    view.tag = 1001;
    bigView.tag = 1002;
    if (sender.selected) {
        view.transform = CGAffineTransformMakeScale(0.01, 0.01);
        [UIView animateWithDuration:0.5 animations:^{
            view.transform = CGAffineTransformIdentity;
            bigView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.2];
        }];

    }else{
        [UIView animateWithDuration:0.5 animations:^{
            view.transform = CGAffineTransformMakeScale(0.01, 0.01);
             bigView.backgroundColor = [UIColor clearColor];
            [bigView removeFromSuperview];
            [view removeFromSuperview];
        }];
    }
}
- (void)addSure{
    UITextField *textField = [self.view viewWithTag:1000];
    UIView *view = [self.view viewWithTag:1001];
    UIView *bigView = [self.view viewWithTag:1002];
    UILabel *warning = [self.view viewWithTag:999];
    if (![textField.text  isEqual: @""]) {
        [UIView animateWithDuration:0.5 animations:^{
            view.transform = CGAffineTransformMakeScale(0.01, 0.01);
            bigView.backgroundColor = [UIColor clearColor];
        }completion:^(BOOL finished) {
            [self.optionsDataSource insertObject:textField.text atIndex:self.optionsDataSource.count];
            [self.collectionView reloadData];
            textField.text = @"";
            [view removeFromSuperview];
            [bigView removeFromSuperview];
        }];
    }else{
        warning.hidden = NO;
        //弹簧动画(usingSpringWithDamping取值0-1，越接近0弹簧效果越明显,initialSpringVelocity接近弹簧初始速度，数值越大，速度越快)
        [UIView animateWithDuration:1
                              delay:0
             usingSpringWithDamping:0.05
              initialSpringVelocity:0
                            options:0
                         animations:^{
                             warning.centerX += 5;
                         }
                         completion:^(BOOL finished){
                             warning.centerX -= 5;
                             warning.hidden = YES;
                         }];

    }
}
//点击种类切换数据源
- (void)optionSbuttonpresented:(UIButton *)sender{
    [self.selectButton setTitleColor:[UIColor colorWithRed:0.1185 green:0.7514 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
    self.selectButton = sender;
    [self.selectButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [self.optionsDataSource removeAllObjects];
    [self.optionsDataSource addObjectsFromArray: self.dataSource[sender.tag - 100]];
    [self.collectionView reloadData];
}
- (void)toBuyList{
    [self putInCoreDataWithData:self.selectDataSource];
    BuyList *butList = [[BuyList alloc]init];
    [self.navigationController pushViewController:butList animated:YES];
    [self.selectDataSource removeAllObjects];
}
- (UIView *)alertView{
    self.addView.bounds = CGRectMake(0, 0, self.view.width * 0.8, self.view.width * 0.8 * 0.6);
    self.addView.center = self.view.center;
    [self.view addSubview:self.addView];
    UIImageView *cloudView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"添加背景"]];
    cloudView.frame = CGRectMake(0, 0, self.addView.width, self.addView.height);
    [self.addView addSubview:cloudView];
    
    UILabel *warning = [[UILabel alloc]init];
    warning.text = @"↓你倒是写点什么啊";
    warning.textColor = [UIColor redColor];
    warning.tag = 999;
    warning.font = [UIFont systemFontOfSize:15];
    warning.textAlignment = NSTextAlignmentCenter;
    warning.hidden = YES;
    [self.addView addSubview:warning];
    warning.sd_layout
    .topSpaceToView(self.addView,20)
    .centerXEqualToView(self.addView)
    .widthRatioToView(self.addView,0.7)
    .heightRatioToView(self.addView,0.2);
    
    UITextField *textField = [[UITextField alloc]init];
    textField.frame = CGRectMake(0, 0, self.addView.width * 0.7, self.addView.height / 4);
    textField.center = cloudView.center;
    textField.tag = 1000;
    textField.placeholder = @"请输入商品名字";
    textField.borderStyle = UITextBorderStyleRoundedRect;
    [self.addView addSubview:textField];
    
    UIButton *sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [sureButton setImage:[UIImage imageNamed:@"确定"] forState:UIControlStateNormal];
    sureButton.bounds = CGRectMake(0,0, self.addView.width * 0.12, self.addView.width * 0.12);
    sureButton.center = CGPointMake(CGRectGetMidX(cloudView.frame),CGRectGetMaxY(textField.frame) + sureButton.bounds.size.height / 2);
    sureButton.alpha = 0.8;
    [sureButton addTarget:self action:@selector(addSure) forControlEvents:UIControlEventTouchUpInside];
    [self.addView addSubview:sureButton];
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelButton setImage:[UIImage imageNamed:@"错"] forState:UIControlStateNormal];
    cancelButton.bounds = CGRectMake(0,0, self.addView.width * 0.12, self.addView.width * 0.12);
    cancelButton.center = CGPointMake(CGRectGetWidth(cloudView.bounds) - cancelButton.bounds.size.width * 1.4,CGRectGetMinY(cloudView.frame) + cancelButton.bounds.size.width);
    cancelButton.alpha = 0.8;
    [cancelButton addTarget:self action:@selector(cancelAdd) forControlEvents:UIControlEventTouchUpInside];
    [self.addView addSubview:cancelButton];
    return self.addView;

}
- (UIView *)returnBigBackGroundView{
    self.bigBackGroundView = [[UIView alloc]initWithFrame:self.view.frame];
    self.bigBackGroundView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.bigBackGroundView];
    return self.bigBackGroundView;
}

- (void)cancelAdd{
    [UIView animateWithDuration:0.5 animations:^{
        self.addView.transform = CGAffineTransformMakeScale(0.01, 0.01);
    }completion:^(BOOL finished) {
        [self.addView removeFromSuperview];
        [self.bigBackGroundView removeFromSuperview];
    }];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (void)getDataFromWeb{
    [MBProgressHUD showHUDAddedTo:self.view animated:true];
    [BaseRequest startGetProductsWithType:self.formArr[0] completionhanlder:^(Response *response) {
        if (response.isSuccess) {
            [self.dataSource addObject:response.resultObject];
            [BaseRequest startGetProductsWithType:self.formArr[1] completionhanlder:^(Response *response) {
                if (response.isSuccess) {
                    [self.dataSource addObject:response.resultObject];
                    [BaseRequest startGetProductsWithType:self.formArr[2] completionhanlder:^(Response *response) {
                        if (response.isSuccess) {
                            [self.dataSource addObject:response.resultObject];
                            [BaseRequest startGetProductsWithType:self.formArr[3] completionhanlder:^(Response *response) {
                                if (response.isSuccess) {
                                    [self.dataSource addObject:response.resultObject];
                                    [BaseRequest startGetProductsWithType:self.formArr[4] completionhanlder:^(Response *response) {
                                        if (response.isSuccess) {
                                            [self.dataSource addObject:response.resultObject];
                                            [BaseRequest startGetProductsWithType:self.formArr[5] completionhanlder:^(Response *response) {
                                                if (response.isSuccess) {
                                                    [MBProgressHUD hideHUDForView:self.view animated:true];
                                                    [self.dataSource addObject:response.resultObject];
                                                    self.optionsDataSource = [NSMutableArray arrayWithArray:self.dataSource[0]];
                                                    [self.collectionView reloadData];
                                                    [[NSUserDefaults standardUserDefaults] setObject:self.dataSource forKey:@"shoppingData"];
                                                }
                                            }];
                                        }
                                    }];
                                }
                            }];
                        }
                    }];
                }
            }];
        }else{
            //弹出错误提示
            UIView *alertView = [self noWebAlertWithMessage:@"请检查网络"];
            [UIView animateWithDuration:0.4 animations:^{
                alertView.alpha = 0.2;
            } completion:^(BOOL finished) {
                alertView.alpha = 0.01;
                [alertView removeFromSuperview];
            }];
        }
    }];

}
- (UIView *)noWebAlertWithMessage:(NSString *)message{
    UIView *view = [[UIView alloc]init];
    view.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds) * 0.3, CGRectGetWidth(self.view.bounds) * 0.1);
    view.center = self.view.center;
    view.backgroundColor = [UIColor colorWithRed:0.1185 green:0.1185 blue:0.1185 alpha:1.0];
    view.alpha = 0.01;
    view.layer.masksToBounds = YES;
    view.layer.cornerRadius = CGRectGetWidth(self.view.bounds) * 0.3 / 4;
    
    UILabel *alertLabel = [[UILabel alloc]init];
    alertLabel.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds) * 0.3, CGRectGetHeight(view.bounds) * 0.4);
    alertLabel.center = view.center;
    alertLabel.text = message;
    alertLabel.textAlignment = NSTextAlignmentCenter;
    [view addSubview:alertLabel];
    [self.view addSubview:view];
    return view;
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.optionsDataSource.count;
}

//自定义 header footer
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
        UICollectionReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath];
    footer.tag = 9000;
    //把footer里的所有子视图删除
    for (UIView * view in footer.subviews) {
        [view removeFromSuperview];
    }
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"添加"] forState:UIControlStateNormal];
    button.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds) /8, CGRectGetWidth(self.view.bounds) /8);
    button.center = CGPointMake(CGRectGetWidth(footer.bounds) - CGRectGetMidX(button.bounds) , CGRectGetMidY(footer.bounds));
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = CGRectGetWidth(footer.bounds) /16;
    [footer addSubview:button];
    [button addTarget:self action:@selector(addCell:) forControlEvents:UIControlEventTouchUpInside];
        return footer;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell";
    CustomProductCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    [cell.name setTitle:self.optionsDataSource[indexPath.row] forState:UIControlStateNormal];
    cell.tag = indexPath.row + 500;
    cell.name.backgroundColor = [UIColor specialRandomColor];
    cell.delegate = self;
    return cell;
}
#pragma mark - CustomProductDelegate
- (void)customProductDelegate:(CustomProductCollectionViewCell *)cell{
    UIImageView *imageView = [self.view viewWithTag:self.selectButton.tag + 200];
    
    //位置
    CABasicAnimation *positionAnimation = [CABasicAnimation animationWithKeyPath:@"position"];
    positionAnimation.fromValue = [NSValue valueWithCGPoint:imageView.center]   ;
    positionAnimation.toValue = [NSValue valueWithCGPoint:self.basketImage.center];
    
    //透明度
    CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    opacityAnimation.fromValue = @(1);
    opacityAnimation.toValue = @(0);
    
    //大小
    CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    scaleAnimation.fromValue = @(1);
    scaleAnimation.toValue = @(0.1);
    
//    //旋转
//    CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
//    scaleAnimation.fromValue = @(1);
//    scaleAnimation.toValue = @(0);
    
    
    //动画组
    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.animations = @[positionAnimation,opacityAnimation,scaleAnimation];
    group.duration = 0.5;
    //线性规律
    group.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    group.fillMode = kCAFillModeForwards;
    //配置动画执行完之后是否回到原位
    group.removedOnCompletion = YES;
    [imageView.layer addAnimation:group forKey:@"group"];
    [self.selectDataSource addObject:cell.name.titleLabel.text];
    NSIndexPath * indexPath = [self.collectionView indexPathForCell:cell];
    [self.optionsDataSource removeObjectAtIndex:indexPath.row];
    [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
    CABasicAnimation *basketScaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    basketScaleAnimation.fromValue = @(1);
    basketScaleAnimation.toValue = @(1.1);
    basketScaleAnimation.removedOnCompletion = NO;
    [self.basketImage.layer addAnimation:basketScaleAnimation forKey:@"transform.scale"];
    [UIView animateWithDuration:0.5 animations:^{
        cell.alpha = 0;
        cell.frame = CGRectMake(1000, 1000, 10, 10);
    } completion:^(BOOL finished) {

    }];
    
    //篮子增加物品动画
    
}
- (void)putInCoreDataWithData:(NSMutableArray *)data{
    NSArray *result = [[NSUserDefaults standardUserDefaults] objectForKey:@"selectList"];
//    result = result.mutableCopy;
    if (result == nil) {
        [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"selectList"];
        [[NSUserDefaults standardUserDefaults] setObject:@[].mutableCopy forKey:@"buyDoneList"];
    }else{
        NSMutableArray *getData = [[NSMutableArray alloc]initWithArray:result];
//        NSMutableArray *replaceArr = [NSMutableArray array];
//        for (NSInteger index = 0; index<data.count; index++) {
//            for (NSInteger index1 = 0; index1 < getData.count; index1 ++) {
//                if (([data[index] isEqualToString:getData[index1]])) {
//                    return ;
//                }else{
//                    [replaceArr addObject:data[index]];
//                    NSLog(@"1111111111%@",replaceArr);
//                }
//            }
//        }
        [getData addObjectsFromArray:self.selectDataSource];
        
        [[NSUserDefaults standardUserDefaults] setObject:getData forKey:@"selectList"];
    }
}
@end
